package com.fs.chatx.module.chat.service;

import com.fs.chatx.core.vo.PageRequest;

import cn.hutool.core.lang.UUID;
import com.fs.chatx.module.chat.entity.ChatMessage;
import com.fs.chatx.module.chat.entity.ChatSession;
import com.fs.chatx.module.chat.enums.RoleType;
import com.fs.chatx.module.chat.mapper.ChatMessageMapper;
import com.fs.chatx.module.chat.mapper.ChatSessionMapper;
import jakarta.annotation.Resource;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.dromara.easyes.core.kernel.Wrapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChatMessageService {
    @Resource
    private ChatMessageMapper chatMessageMapper;
    @Resource
    private ChatSessionMapper chatSessionMapper;


    // 添加消息到会话
    public void addMessage(ChatMessage message) {
        message.setMessageId(UUID.randomUUID().toString());
        message.setCreateTime(LocalDateTime.now());
        chatMessageMapper.insert(message);
        // 更新会话最后更新时间
        ChatSession chatSession = chatSessionMapper.selectById(message.getSessionId());
        if (chatSession != null) {
            ChatSession sessionData = new ChatSession();
            sessionData.setSessionId(message.getSessionId());
            sessionData.setUpdateTime(LocalDateTime.now());
            if ( message.getRole().equals(RoleType.USER.getType())) {
                sessionData.setTitle(message.getContent());
            }
            chatSessionMapper.updateById(sessionData);
        }
    }

    // 获取对话历史（新增分页参数）
    public List<ChatMessage> getHistory(String sessionId, PageRequest pageRequest) {
        if (pageRequest.getPage() < 1 || pageRequest.getPageSize() < 1) {
            throw new IllegalArgumentException("page和pageSize必须大于等于1");
        }

        Wrapper<ChatMessage> wrapper = new LambdaEsQueryWrapper<>(ChatMessage.class)
                .eq(ChatMessage::getSessionId, sessionId)
                .orderByDesc(ChatMessage::getCreateTime)
                .limit((pageRequest.getPage() - 1) * pageRequest.getPageSize(), pageRequest.getPageSize());
        return chatMessageMapper.selectList(wrapper).stream()
                .sorted((o1, o2) -> o1.getCreateTime().compareTo(o2.getCreateTime()))
                .collect(Collectors.toList());
    }

}
